package com.lepu.app.fun.chat.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;

import com.app.config.UserConfig;
import com.app.utils.CharacterParser;
import com.app.utils.Const;
import com.app.utils.LoginUtil;
import com.app.utils.ObserverConst;
import com.app.utils.Setting;
import com.core.lib.application.BaseFragmentActivity;
import com.core.lib.core.ApiClient;
import com.core.lib.core.AsyncRequest;
import com.core.lib.utils.Observer;
import com.core.lib.utils.ObserverManager;
import com.core.lib.utils.main.LogUtilBase;
import com.core.lib.widget.MyDialog;
import com.lepu.app.fun.chat.adapter.ChatSessionAdapter;
import com.lepu.app.fun.chat.bean.BeanDoctorNotice;
import com.lepu.app.fun.chat.bean.ChatSession;
import com.lepu.app.fun.chat.core.ChatDAO;
import com.lepu.app.fun.chat.core.ChatManager;
import com.lepu.app.fun.chat.util.ChatConst;
import com.lepu.app.fun.chat.util.ChatUtil;
import com.lepu.app.fun.chat.util.Constants;
import com.lepu.app.widget.CustomTopBarNew;
import com.lepu.app.widget.CustomTopBarNew.OnTopbarNewLeftLayoutListener;
import com.lepu.app.widget.CustomTopBarNew.OnTopbarNewRightButtonListener;
import com.lepu.pasm.R;

public class DoctorMainActivity extends BaseFragmentActivity implements
		OnTopbarNewLeftLayoutListener, OnTopbarNewRightButtonListener,
		Observer, AsyncRequest {

	private static final String REQUEST_DATA = "request_data";

	private ListView mDataListView = null;
	private ChatSessionAdapter mDataAdapter = null;
	private List<ChatSession> mDataList = null;

	private List<BeanDoctorNotice> mNoticeList = null;
	private View mHeaderView = null;

	@Override
	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.chat_doctor_main_activity);

		init();
	}

	@Override
	public void onResume() {
		super.onResume();

		ObserverManager.getInstance().addObserver(
				ObserverConst.NOTIFY_CHAT_DOCTOR_SESSION, this);

		refreshData();
	}

	@Override
	public void onPause() {
		super.onPause();

		ObserverManager.getInstance().removeObserver(
				ObserverConst.NOTIFY_CHAT_DOCTOR_SESSION);
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
	}

	/**
	 * 添加页面动画，需要重写这个方法，
	 */
	@Override
	public void onBackPressed() {
		finish(true);
	}

	@Override
	public void onTopbarLeftLayoutSelected() {
		finish(true);
	}

	@Override
	public void onTopbarRightButtonSelected() {
		Intent intent = new Intent(this, DoctorMyActivity.class);
		startActivity(intent, true);
	}

	/**
	 * 初始化方法
	 */
	@SuppressLint("InflateParams")
	private void init() {
		// topbar
		CustomTopBarNew topbar = (CustomTopBarNew) findViewById(R.id.topbar);
		topbar.setTopbarTitle("主治医生");
		topbar.setonTopbarNewLeftLayoutListener(this);
		topbar.setRightText("我的医生");
		topbar.setOnTopbarNewRightButtonListener(this);

		mHeaderView = LayoutInflater.from(this).inflate(
				R.layout.chat_doctor_main_notice_header_layout, null);

		mDataListView = (ListView) findViewById(R.id.dataListView);
		mDataListView.setOnItemClickListener(mOnItemClickListener);
		mDataListView.setOnItemLongClickListener(mOnItemLongClickListener);
		mDataListView.addHeaderView(mHeaderView);

		mDataList = new ArrayList<ChatSession>();
		mDataAdapter = new ChatSessionAdapter(this, mDataList);
		mDataListView.setAdapter(mDataAdapter);
		
		requestNotice();
	}

	private void initNotice() {
		
		TextView contentTextView = (TextView) mHeaderView
				.findViewById(R.id.contentTextView);
		TextView timeTextView = (TextView) mHeaderView
				.findViewById(R.id.timeTextView);
		TextView newCountTextView = (TextView) mHeaderView.findViewById(R.id.newCountTextView);

		if (mNoticeList != null && mNoticeList.size() > 0) {

			LoginUtil.updateChatNoticeNewCount(mNoticeList.size());

			BeanDoctorNotice.saveNoticeDb(mNoticeList);
			
			BeanDoctorNotice item = mNoticeList.get(0);
			
			newCountTextView.setVisibility(View.VISIBLE);
			
			timeTextView.setText(item.RecordCreateTime);
			contentTextView.setText(item.Content);
			newCountTextView.setText(String.valueOf(LoginUtil.getChatNoticeCount()));

		} else {

			int noticeCount = LoginUtil.getChatNoticeCount();
			if(noticeCount > 0){

				List<BeanDoctorNotice> dataArrayList = BeanDoctorNotice
						.getNoticeListItem(LoginUtil.getUserId());
				if(dataArrayList != null && dataArrayList.size() > 0){

					BeanDoctorNotice item = dataArrayList.get(0);
					newCountTextView.setVisibility(View.VISIBLE);

					timeTextView.setText(item.RecordCreateTime);
					contentTextView.setText(item.Content);
					newCountTextView.setText(String.valueOf(noticeCount));
				}else{
					newCountTextView.setVisibility(View.GONE);

					timeTextView.setText("");
					contentTextView.setText("查看最新公告");
				}
			}else{
				newCountTextView.setVisibility(View.GONE);

				timeTextView.setText("");
				contentTextView.setText("查看最新公告");
			}
		}
	}

	public void refreshData() {
		if (mDataList != null && mDataList.size() > 0) {
			mDataList.clear();
		}

		List<ChatSession> dataList = ChatManager.getInstance()
				.getChatSessionsWithProductIcon();
		if (dataList != null && dataList.size() > 0) {
			mDataList.addAll(dataList);
		}
		mDataAdapter.notifyDataSetChanged();
	}

	public void requestNotice() {

		String refreshTime = UserConfig.getConfigString(this,
				Const.CONFIG_APP_CHAT_NOTICE_REFRESH_TIME,"");

		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject params = new JSONObject();
		try {
			params.put("DeviceID", Setting.DEVICEID);
			params.put("ApplicationID", Setting.APPLICATIONID);

			params.put("PatientID", LoginUtil.getUserId());
			params.put("LoginToken", LoginUtil.getLoginToken());

			params.put("RefreshTime", refreshTime);
		} catch (Exception e) {
		}
		map.put("ht", params);

		ApiClient.http_post_main(Setting.getMyDoctorNewNoticeListUrl(), map,
				null, this, REQUEST_DATA, true, false, true);
	}

	OnItemClickListener mOnItemClickListener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			if (position == 0) {
				
				mNoticeList = null;
				LoginUtil.clearChatNoticeCount();
				initNotice();
				
				// 我的公告板
				Intent intent = new Intent(DoctorMainActivity.this,
						DoctorMainNoticeActivity.class);
				startActivity(intent, true);
			} else {
				// 聊天界面
				ChatSession item = mDataList.get(position - 1);
				ChatUtil.jumpChat(DoctorMainActivity.this, item,
						ChatConst.TYPE_ONLINE_CHAT_DOCTOR_MY);
			}
		}
	};

	AdapterView.OnItemLongClickListener mOnItemLongClickListener = new AdapterView.OnItemLongClickListener() {
		@Override
		public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {

			if(position > 0){
				deleteItem(position-1);
			}

			return true;
		}
	};

	public void deleteItem(final int position) {

		String message = "您确定删除这个聊天记录吗？";
		MyDialog dialog = new MyDialog(this)
				.setMessage(message)
				.setNegativeButton(R.string.app_cancel,
						R.drawable.btn_cancel_selector, R.color.color_white,
						new View.OnClickListener() {

							@Override
							public void onClick(View v) {

							}
						})
				.setPositiveButton(R.string.app_ok, R.drawable.btn_ok_selector,
						R.color.color_white, new View.OnClickListener() {

							@Override
							public void onClick(View v) {

								long sessionID = mDataList.get(position).getSessionId();
								ChatDAO.getInstance().clearChatHistoryBySession(sessionID);

								mDataList.remove(position);
								mDataAdapter.notifyDataSetChanged();
							}
						});

		dialog.create(null);
		dialog.showMyDialog();
	}


	@Override
	public void RequestComplete(Object object, Object data) {
		if (object.equals(REQUEST_DATA)) {
			String result = (String) data;
			mNoticeList = BeanDoctorNotice.parseListInfo(result);

			if(mNoticeList != null && mNoticeList.size() > 0){
				try {
					JSONObject jsonObject = new JSONObject(result);
					JSONObject obj1 = (JSONObject) jsonObject.get("Result");
					JSONObject obj2 = (JSONObject) obj1.get("DetailInfo");

					String refreshTime = obj2.optString("RefreshTime");
					UserConfig.setConfig(this, Const.CONFIG_APP_CHAT_NOTICE_REFRESH_TIME,refreshTime);
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}

			initNotice();
		}
	}

	@Override
	public void RequestError(Object object, int errorId, String data) {
		if (object.equals(REQUEST_DATA)) {
		}
	}

	/**
	 * main thread
	 */
	@SuppressLint("NewApi")
	@Override
	public void notify(String name, Object sender, Object data) {

		if (name.equals(ObserverConst.NOTIFY_CHAT_DOCTOR_SESSION)) {

			//
			if (data == null) {
				LogUtilBase.LogD(null, "handleMessage: ChatSession is null");
				return;
			}

			ChatSession session = (ChatSession) data;
			int msgWhat = (Integer) sender;

			switch (msgWhat) {
			case Constants.Chat.CHAT_MESSAGE_RECEIVED:
				LogUtilBase.LogD(null, "Session List:CHAT_MESSAGE_RECEIVED");
				boolean isNew = true;
				for (int i = 0; i < mDataList.size(); i++) {
					if (mDataList.get(i).getSessionId() == session
							.getSessionId()) {
						mDataList.set(i, session);
						isNew = false;
						break;
					}
				}
				if (isNew) {
					mDataList.add(session);
				}
				// handleNewMessageCount(0);
				mDataAdapter.notifyDataSetChanged();
				break;
			case Constants.Chat.CHAT_MESSAGE_CHANGED:
				LogUtilBase.LogD(null, "Chatting Room:CHAT_MESSAGE_CHANGED");
				for (int i = 0; i < mDataList.size(); i++) {
					if (mDataList == null || mDataList.get(i) == null
							|| mDataList.get(i).getLastMsgContent().isEmpty()) {
						break;
					}
					if (mDataList.get(i).getSessionId() == session
							.getSessionId()) {
						mDataList.set(i, session);
						isNew = false;
						break;
					}
				}
				// handleNewMessageCount(0);
				if (mDataAdapter != null) {
					mDataAdapter.notifyDataSetChanged();
				}
				break;
			}
		}
	}

}
